<template>
  <div class="checkbox">
    <el-checkbox v-model="checkedAll"  @change="handleCheckedAll">
      全选
    </el-checkbox>
    <span class="numerical">{{ numerical }}</span>
    <el-checkbox-group v-model="checkedPolluteList" @change="handleCheckedChange"  >
      <el-checkbox v-for="(item,index) in dataGrid"  
      :label="item" :key="index">{{ item[defaultProps.label] }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script>
export default {
  props: {
    defaultProps: Object,
    checkedKeys: Array, // 默认选中
    dataGrid: Array
  },
  watch: {
    checkedPolluteList(n) {
      this.$emit('change', n);
    },
    checkedKeysAndDataGrid(n) {
      const { checkedKeys, dataGrid } = n;
      if (checkedKeys.length && dataGrid.length) {
        const checkedKeys = this.checkedKeys;
        this.checkedPolluteList = this.dataGrid.filter(v => checkedKeys.includes(v[this.defaultProps.id]));
        this.checkedAll = this.checkedPolluteList.length === this.dataGrid.length;
      }
    }
  },
  data() {
    return {
      checkedAll: false,
      checkedPolluteList: []
    };
  },
  computed: {
    numerical() {
      const total = this.dataGrid.length;
      const checked = this.checkedPolluteList.length;
      return `${checked}/${total}`;
    },
    checkedKeysAndDataGrid() {
      const { checkedKeys, dataGrid } = this;
      return {
        checkedKeys, dataGrid
      };
    }
  },
  methods: {
    resert() {
      this.checkedAll = false;
      this.checkedPolluteList = [];
    },
    handleCheckedChange(val) {
      if (val.length === this.dataGrid.length) {
        this.checkedAll = true;
      } else {
        this.checkedAll = false;
      }
    },
    handleCheckedAll(val) {
      if (val) {
        this.checkedPolluteList = this.dataGrid;
      } else {
        this.checkedPolluteList = [];
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.checkbox{
  .numerical {
    float: right;
    color: #909399;
  }
}
</style>